package com.admin.kotlintest.broudcaust

import android.app.Notification
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.os.Build
import android.support.v4.app.NotificationCompat
import cn.bmob.push.PushConstants
import com.admin.kotlintest.R
import com.admin.kotlintest.bean.InstallationMsg
import com.admin.kotlintest.utils.GsonUtils
import com.socks.library.KLog
import android.app.PendingIntent.FLAG_CANCEL_CURRENT
import cn.bmob.v3.Bmob.getApplicationContext
import com.admin.kotlintest.activity.HomeActivity
import org.json.JSONObject


@Suppress("DEPRECATION")
/**
 * Created by 吴昶 on 2018/4/20.
 */
class MyPushMessageReceiver:BroadcastReceiver(){


    override fun onReceive(context: Context?, intent: Intent?) {
        KLog.d("=============")
        if(intent!!.action == PushConstants.ACTION_MESSAGE){
            KLog.d("bmob", "客户端收到推送内容："+intent.getStringExtra("msg"))
            var msg=intent.getStringExtra("msg")
            if(msg.indexOf("alert")!=-1){
                KLog.d(msg)
                var alert=JSONObject(msg).getString("alert")
                KLog.d(alert)
                show(context,alert)
            }else{
                show(context,msg)
            }
        }
    }


    fun show(context: Context?,msg:String){
        var inmsg=GsonUtils.paresJsonWithGon(msg,InstallationMsg::class.java)
        var notifyManager = context!!.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        var builder= NotificationCompat.Builder(context)
        var intent = if(inmsg.action==""){
            Intent(getApplicationContext(), HomeActivity::class.java)
        }else{
            Intent(inmsg.action)
        }
        var pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent.FLAG_CANCEL_CURRENT)
        builder.setSmallIcon(R.mipmap.ic_launcher_round)
                .setLargeIcon(BitmapFactory.decodeResource(context.resources,R.mipmap.ic_launcher_round))
                .setContentTitle(inmsg.title)
                .setContentText(inmsg.msg)
                .setSubText(inmsg.subtitle)
                .setAutoCancel(true)
                .setWhen(System.currentTimeMillis())
                .setContentIntent(pendingIntent)
        notifyManager.notify(0,builder.build())
    }



}